package com.graduation.lastproject.controller.business.businessHighActive;


import com.graduation.lastproject.entity.*;
import com.graduation.lastproject.service.business.businessBasicActive.BusinessService;
import com.graduation.lastproject.service.business.businessHighActive.BusinessHighService;
import com.sun.xml.internal.ws.resources.HttpserverMessages;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping(value = "/businessHigh")
public class BusinessHighControl {

    @Autowired
    private BusinessHighService businessHighService;

    @Autowired
    BusinessService businessService;

    @Value("${spring.fileupload.destination}")
    private String destination;


    //更新酒店字段信息
    @RequestMapping(value = "/uploadFileEdit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> uploadFileEdit(HttpServletRequest request){
        Map<String,Object> result=new HashMap<>() ;
        Map<String,Object> hotelInfo=parameters(request);
        Map<String, String[]> map1 = request.getParameterMap();
        String serviceFacilities= Arrays.toString((String[])map1.get("serviceFacilities"));
        String hotelRoomType=Arrays.toString((String[])map1.get("hotelRoomType"));
        hotelInfo.put("serviceFacilities",serviceFacilities);
        hotelInfo.put("hotelRoomType",hotelRoomType);
        int i=businessHighService.uploadFileEdit(hotelInfo);
        result.put("msg",i == 1 ? "修改成功" : "修改失败");
        return result;
    }


    //更新酒店图片信息
    //上传酒店图片信息
    @RequestMapping(value = "/uploadPhotoEdit",method = RequestMethod.POST)
    @ResponseBody
    public Object uplodePhoto(HttpServletRequest request, @RequestParam("files") MultipartFile[] files) throws IOException {
        Map<String,Object> result= new HashMap<>();
     /*   if(files.length <2){
            result.put("msg","请修改所有图片再选择修改");
            return result;
        }*/
        String id=request.getParameter("hotelid");
        String main=request.getParameter("mainPicLocation");
        String big=request.getParameter("big");
        String dou=request.getParameter("dou");
        String cir=request.getParameter("cir");
        String cou=request.getParameter("cou");
        String mainLong="D:\\\\IdeaProjects\\\\lastproject\\\\src\\\\main\\\\resources"+main.replace("/","\\\\");
        String bigLong="D:\\\\IdeaProjects\\\\lastproject\\\\src\\\\main\\\\resources"+big.replace("/","\\\\");
        String doubleLong="D:\\\\IdeaProjects\\\\lastproject\\\\src\\\\main\\\\resources"+dou.replace("/","\\\\");
        String cirLong="D:\\\\IdeaProjects\\\\lastproject\\\\src\\\\main\\\\resources"+cir.replace("/","\\\\");
        String couLong="D:\\\\IdeaProjects\\\\lastproject\\\\src\\\\main\\\\resources"+cou.replace("/","\\\\");
        /*//根据酒店主键id清楚hotel_picInfo记录数据
        int j =businessHighService.deleteHotelPicInfo(hotelId);
        if(j!=1){
            result.put("msg","操作失败");
            return "business/index";
        }*/
        String msg = "";
        int i=0;
        if(null != files && files.length>0){
            for(MultipartFile file : files){
                // 测试MultipartFile接口的各个方法
                System.out.println("文件组件名称Name=" + file.getName());
                System.out.println("文件原名称OriginalFileName=" + file.getOriginalFilename());
                System.out.println("文件大小Size=" + file.getSize() + "byte or " + file.getSize()/1024 + "KB");
                if(file.getSize()>0){
                     msg=saveInfo(file,destination,id,i);
                     if(i==0){
                         File oldFile=new File(mainLong);
                         oldFile.delete();
                     }else if(i==1){
                         File oldFile=new File(bigLong);
                         oldFile.delete();
                     }else if(i==2){
                         File oldFile=new File(doubleLong);
                         oldFile.delete();
                     }else if(i==3){
                         File oldFile=new File(cirLong);
                         oldFile.delete();
                     }else if(i==4){
                         File oldFile=new File(couLong);
                         oldFile.delete();
                     }
                }
                i++;      //i [0,1,2,3,4} 判断
            }
            if(!msg.equals("成功")){
                result.put("msg","未上传任何文件");
            }else {
                result.put("msg",msg);
            }
            return result;
        }else {
            result.put("msg","上传失败");
            return result;
        }
    }


    //图片保存
    private String saveInfo(MultipartFile file, String destination,String id,int time) throws IOException {
        // 获取上传的文件名称，并结合存放路径，构建新的文件名称
        String filename = file.getOriginalFilename();
        String fileExtName = String.valueOf(System.currentTimeMillis());
        String filepathName=fileExtName+"_"+filename;
        File filepath = new File(destination, filepathName);

        // 判断路径是否存在，不存在则新创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        // 将上传文件保存到目标文件目录
        file.transferTo(filepath);
        String path="\\\\static\\\\img\\\\hotelPicInfo"+"\\\\"+filepathName;
        String realPath=path.replace("\\\\", "/");
        Map<String,Object> info=new HashMap<>();
        info.put("picLocation",realPath);
        info.put("id", id);
        info.put("time",time);
        int i=businessHighService.updataPicInfo(info);
        return "成功";
    }

    /*获取当前登录用户的酒店订单*/
    @RequestMapping(value = "/getBookorderListPage")
    @ResponseBody
    public PageMore<Bookorder> getBookorderListPage(HttpServletRequest request,Bookorder bookorder){
        /*获取商家的电话*/
        String bphone=((Business)request.getSession().getAttribute("businessInfo")).getBphone();
        bookorder.setUserPhone(bphone); /*储存的商家电话*/
        PageMore<Bookorder> pageMore=new PageMore<>();
        /*获取当前商家订单总数*/
        int total =businessHighService.getOrderTotal(bookorder);
        pageMore.setTotal(total);
        /*获取当前商家订单信息*/
        List<Bookorder> list=businessHighService.getOrderInfoListPage(bookorder);
        pageMore.setRows(list);
        return pageMore;

    }

    /*获取当前登录用户的评论订单*/
    @RequestMapping(value = "/getBReviewListPage")
    @ResponseBody
    public PageMore<Review> getReviewListPage(HttpServletRequest request,Review review){
          /*获取当前商家的电话*/
        String bphone=((Business)request.getSession().getAttribute("businessInfo")).getBphone();
        review.setUserPhone(bphone); /*储存的商家电话*/
        PageMore<Review> pageMore=new PageMore<>();
         /*获取评论总数*/
        int total=businessHighService.getBReviewTotal(review);
        pageMore.setTotal(total);
         /*获取所有评论信息*/
        List<Review> list=businessHighService.getBReviewInfoListPage(review);
        pageMore.setRows(list);
        return  pageMore;
    }

    /*商家回复*/
    @RequestMapping(value = "/businessReturnReview" , method =  RequestMethod.POST)
    @ResponseBody
    public  Object businessReturnReview(HttpServletRequest request){
        Map<String,Object> result=new HashMap<>();
        Map<String,Object> map=parameters(request);
        /*只更新内容 评论时间以用户评论时间为准*/
        int i=businessHighService.businessReturnReview(map);
        result.put("msg",i==1 ? "回复成功" : "回复失败");
        return result;
    }

    /*统计年份收入*/
    @RequestMapping(value = "getTotalInPrice" , method = RequestMethod.POST)
    @ResponseBody
    public Object getTotalInPrice(HttpServletRequest request){
         /*获取当前商家的电话*/
        String bphone=((Business)request.getSession().getAttribute("businessInfo")).getBphone();
        String year=request.getParameter("year");
        List<BusinessIncom> list=businessHighService.getTotalInPrice(bphone,year);
        return  list;
    }



    //request 转 map
    private final Map<String, Object> parameters(HttpServletRequest request) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        if (request != null) {
            Enumeration<String> keys = request.getParameterNames();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                try {
                    parameters.put(key, request.getParameter(key));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return parameters;
    }

    public static void deleteFile(File file) {
        if (file.exists()) {//判断路径是否存在
            if (file.isFile()) {//boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。
                file.delete();
            } else {//不是文件，对于文件夹的操作
                //保存 路径D:/1/新建文件夹2  下的所有的文件和文件夹到listFiles数组中
                File[] listFiles = file.listFiles();//listFiles方法：返回file路径下所有文件和文件夹的绝对路径
                for (File file2 : listFiles) {
					/*
					 * 递归作用：由外到内先一层一层删除里面的文件 再从最内层 反过来删除文件夹
					 *    注意：此时的文件夹在上一步的操作之后，里面的文件内容已全部删除
					 *         所以每一层的文件夹都是空的  ==》最后就可以直接删除了
					 */
                    deleteFile(file2);
                }
            }
            file.delete();
        } else {
            System.out.println("该file路径不存在！！");
        }
    }
}
